from ete2 import Tree
import UserModel
import MCTS
import os

class Experiment(object):

    MAXDISTANCE = 0.01
    MAXITERATIONS = 100

    def __init__(self, filename, number_of_images, setsize=10):
        self.setsize = setsize
        self.number_of_images = number_of_images
        self.user = UserModel.UserModel(self.number_of_images, self.setsize, filename)
        self.target = self.user.getTarget()
        #print 'Target image = ', self.user.target
        #self.mcts = MCTS.OMC(filename, proximity_type, clustering_type, number_of_images, self.target)
        self.treesearch = MCTS.GAMMA(filename, number_of_images, self.target)
        
    def Run(self):
        chosen_image = None
        chosen_distance = 1
        iteration = 0
        '''images = self.mcts.RandomImages(self.setsize)
        chosen_image = self.user.Select(images)
        self.mcts.ModifyTree(images, chosen_image)'''
        avnodes = []
        while(chosen_distance > Experiment.MAXDISTANCE) and iteration < Experiment.MAXITERATIONS:
            iteration += 1
          #  print 'Iteration number', iteration
            images, avnodes_to_chosen_image = self.treesearch.ChooseImages(self.setsize)
            avnodes.append(avnodes_to_chosen_image)
            #print 'Images = ', images
#            chosen_image, chosen_distance = self.user.Select(images)
            chosen_image, relevance_scores, average_distance, chosen_distance, minimum_distance = self.user.Select(images)
            #print 'Chosen image = ', chosen_image
            distance_to_target = self.treesearch.ModifyTree(images, chosen_image)
         #####   print distance_to_target
        #print 'We have found the target!'
        print 'Number of iterations = ', iteration
        Terminated = False
        if iteration < Experiment.MAXITERATIONS:
            Terminated = True 
        return Terminated, avnodes, iteration

File = 'features-1000'
NumberofImages = 1000
setsize = 10
fileResultAvNodes = os.path.dirname(__file__) + '-files/' + 'AvegerageNodes1' + File

#f=open(fileResultAvNodes,  'w')
#f.writelines('')
#f.close()

expnumber = 100
iterations = 0
for i in range(expnumber):
    print 'Experiment number = ', i
    exp = Experiment(File, NumberofImages, setsize)
    Terminated, avnode, iteration = exp.Run()
    iterations += iteration
    if Terminated:
        while len(avnode) < Experiment.MAXITERATIONS: 
            avnode.append(0)
        stravnode = map(str, avnode)
        avnodewrite = ' '.join(stravnode)+'\n'
        f=open(fileResultAvNodes,  'a')
        f.writelines(avnodewrite)
    else:
        print 'Failed'
f.close()
print (1.0*iterations/expnumber)